package com.atguigu.webflux;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Jungle
 * @create 2024-01-13 8:50
 */

@Slf4j
public class Main {
    public static void main(String[] args) throws IOException {
        AtomicInteger count = new AtomicInteger();
        // 快速字节编写一个能处理请求的服务器

        //快速自己编写一个能处理请求的服务器

        //1、创建一个能处理Http请求的处理器。 参数：请求、响应； 返回值：Mono<Void>：代表处理完成的信号
        HttpHandler handler = (ServerHttpRequest request,
                               ServerHttpResponse response) -> {
            URI uri = request.getURI();
            log.info("请求进来 ==>{}", uri);
            // 编写请求处理的业务，给浏览器写一个内容URL + "Hello~! "
            //   response.getHeaders();  //获取响应头
            //   response.getCookies();  //获取cookie
            //   response.getStatusCode();  //获取响应状态码
            //   response.bufferFactory();  //buffer工厂
            //   response.writeWith();      //把xxx写出去
            //   数据的发布者 ：Mono<DataBuffer>、Flux<DataBuffer>
            // 创建 响应的 DataBuffer
            DataBufferFactory factory = response.bufferFactory();
            // 数据buffer
            DataBuffer wrap = factory.wrap((uri + "===>hello"+ count.getAndIncrement()).getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        };
        //2、启动一个服务器，监听8080端口，接受数据，拿到数据交给HttpHandler进行请求处理
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
        //3、启动netty服务器
        HttpServer.create()
                .host("localhost")
                .port(8080)
                .handle(adapter)  //用指定的处理器处理请求
                .bindNow(); //现在就绑定


        System.out.println("服务器启动完成》》》》监听8080，接受请求");
        System.in.read();
        System.out.println("服务器停止》》》》");
    }
}

